<template>
  <a-modal :title="title" :width="1250" :visible="visible"  @cancel="handleCancel"
    :cancelText="$t('systemManagement.close')" wrapClassName="ant-modal-cust-warp"
    style="top:5%;height: 100%;overflow-y: hidden">
    <template slot="footer">
      <!-- <a-button style="margin-left: 8px" v-print="'#reportPrintDetail'" icon="printer">{{$t('reportQuery.print')}}</a-button>   
      <a-button v-if="btnEnableList.indexOf(5) > -1"  style="margin-left: 8px" @click="generatePrintData" icon="printer">{{$t('inPrint.other') + $t('reportQuery.print')}}</a-button> -->
      <a-button style="margin-left: 8px" @click="handleCancel">{{$t('systemManagement.close')}}</a-button>   
               
    </template>
    <!-- 查询区域 -->
    
    <div class="table-page-search-wrapper" v-show="false">
          <a-form layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <a-col :md="6" :sm="24">
                <a-form-item :label="$t('reportQuery.documentNo')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input :placeholder="$t('reportQuery.pleaseEnterTheDocumentNumber')" v-model="queryParam.number"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item :label="$t('reportQuery.productInformation')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-input :placeholder="$t('reportQuery.barcodeModel')" v-model="queryParam.materialParam"></a-input>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item :label="$t('reportQuery.documentDate')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-range-picker
                    style="width: 100%"
                    v-model="queryParam.createTimeRange"
                    :default-value="defaultTimeStr"
                    format="YYYY-MM-DD"
                    :placeholder="[$t('reportQuery.startTime'), $t('reportQuery.endTime')]"
                    @change="onDateChange"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24" >
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                  <a-button type="primary" @click="searchQuery">{{$t('reportQuery.query')}}</a-button>
                  <a @click="handleToggleSearch" style="margin-left: 8px">
                    {{ toggleSearchStatus ? $t('reportQuery.putAway'): $t('reportQuery.open') }}
                    <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
                  </a>
                </span>
              </a-col>
              
              <template v-if="toggleSearchStatus">
                <a-col :md="6" :sm="24">
                  <a-form-item :label="$t('reportQuery.transferOutWarehouse')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-select style="width: 200px" :placeholder="$t('purchasingManagement.selectWarehousingWarehouse')" 
                    v-model="queryParam.depotIdF" allowClear >
                      <!-- @select="depotSelectChange" -->
                        <a-select-opt-group>
                          <span slot="label">{{$t('inPrint.self')}}</span>
                          <a-select-option v-for="(item, index) in selfDepot" :key="index" :value="item.id">
                          {{ item.depotName || item.name }}
                        </a-select-option>
                        </a-select-opt-group>
                        <a-select-opt-group :label="$t('inPrint.other')">
                          <a-select-option v-for="(item, index) in othoerDepot" :key="index" :value="item.id">
                          {{ item.depotName || item.name }}
                        </a-select-option>
                        </a-select-opt-group>
                      </a-select>
                    </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item :label="$t('reportQuery.transferInWarehouse')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-select style="width: 200px" :placeholder="$t('reportQuery.pleaseSelectWarehouse')" 
                    v-model="queryParam.depotId" allowClear >
                      <!-- @select="depotSelectChange" -->
                        <a-select-opt-group>
                          <span slot="label">{{$t('inPrint.self')}}</span>
                          <a-select-option v-for="(item, index) in selfDepot" :key="index" :value="item.id">
                          {{ item.depotName || item.name }}
                        </a-select-option>
                        </a-select-opt-group>
                        <a-select-opt-group :label="$t('inPrint.other')">
                          <a-select-option v-for="(item, index) in othoerDepot" :key="index" :value="item.id">
                          {{ item.depotName || item.name }}
                        </a-select-option>
                        </a-select-opt-group>
                      </a-select>
                  </a-form-item>
                </a-col>
                <a-col :md="6" :sm="24">
                  <a-form-item :label="$t('defaultTranslate.operator')" :labelCol="{ span: 5 }"
                    :wrapperCol="{ span: 18, offset: 1 }">
                    <a-select :placeholder="$t('defaultTranslate.operator')" style="width: 200px" v-model="queryParam.creator">
                      <a-select-option v-for="(item,index) in userList" :key="index" :value="item.id">
                      {{ item.userName }}
                        </a-select-option>
                      </a-select>
                  </a-form-item>
                </a-col>  
                <a-col :md="6" :sm="24">
                  <a-form-item :label="$t('reportQuery.remarks')" :labelCol="labelCol" :wrapperCol="wrapperCol">
                    <a-input :placeholder="$t('reportQuery.pleaseEnterComments')" v-model="queryParam.remark"></a-input>
                  </a-form-item>
                </a-col>
              </template>
              
              <a-col :md="6" :sm="24" >
                <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons table-operator">
                  <!-- <ColumnsSetting style="ma" @columnsChange="columnsChange" :columns="columns"></ColumnsSetting> -->
                  <a-button style="margin-left: 8px" v-print="'#reportPrint'" icon="printer">{{$t('reportQuery.print')}}</a-button>
                  <a-button v-if="btnEnableList.indexOf(5) > -1"  style="margin-left: 8px" @click="generatePrintData" icon="printer">{{$t('inPrint.other') + $t('reportQuery.print')}}</a-button>
                  <a-button v-if="btnEnableList.indexOf(3) > -1" :loading="downLoading" style="margin-left: 8px" @click="exportExcel" icon="download">{{$t('reportQuery.export')}}</a-button>
                </span>
              </a-col>
            </a-row>
            
            <template v-if="toggleSearchStatus">
                 
              </template>
          </a-form>
        </div>
    <!-- table区域-begin -->
    <section ref="print" id="reportPrintDetail">
    <a-table v-if="selectType === 'list'" bordered ref="table" size="middle" :columns="columns"
      :dataSource="dataSource" :pagination="ipagination" :loading="loading"
      :selection="{key:'id'}"
      :customRow="rowAction" @change="handleTableChange">
      <span slot="numberCustomRender" slot-scope="text, record">
        <a @click="myHandleDetail(record)">{{ record.number }}</a>
      </span>
    </a-table>
    </section>

    <!-- table区域-end -->
    <!-- 表单区域 -->
    <bill-detail ref="billDetail"></bill-detail>
  </a-modal>
</template>

<script>
import BillDetail from '@/views/bill/dialog/BillDetail'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { findBillDetailByNumber,findBySelectSup,findBySelectCus,getUserList  } from '@/api/api'
import { getAction } from '@/api/manage'
import { getNowFormatYear,openDownloadDialog, sheet2blob } from "@/utils/util"
import { filterObj } from '@/utils/util'
import moment from 'moment';
import {getLanCode} from '@/lang';
import Vue from 'vue';
export default {
  name: 'LinkBillList',
  mixins: [JeecgListMixin],
  components: {
    BillDetail ,
      VNodes: {
        functional: true,
        render: (h, ctx) => ctx.props.vnodes,
      }
  },
  data() {
    return {
      title: this.$t('reportQuery.allocationDetails'),
      visible: false,
      disableMixinCreated: true,
      selectedRowKeys: [],
      selectedDetailRowKeys: [],
      selectBillRows: [],
      selectedRows:[],
      selectBillDetailRows: [],
      showType: 'basic',
      selectType: 'list',
      linkNumber: '',
      deliveryMethod: '',
      arrivalTimeStr: '',
      organId: '',
      depotId: '',
      discount: '',
      deposit: '',
      remark: '',
      checkDepotId:'',
      linkId:'',
      supList:[],
      cusList:[],
      userList:[],
      defaultTimeStr:[],
      anotherDepotList:[],
      selfDepot:[],
      othoerDepot:[],
      toggleSearchStatus:true,
      
      queryParam: {
          organId: '',
          number: '',
          materialParam:'',
          depotId: '',
          beginTime: getNowFormatYear() + '-01-01',
          endTime: moment().format('YYYY-MM-DD'),
          type: '',
          remark: '',
          subType:'',
          creator:'',
          materialId:'',
        },
      noNeedNextDialogArray: ['ZPHX', 'ZFYS', 'YSKD', 'FYF','YFKD'],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
        // 表头
        columns: [
          {
            title: this.$t('defaultTranslate.lineNumber'), dataIndex: 'rowIndex', width:40, align:"center",
            customRender:function (t,r,index) {
              return (t !== '合计') ? (parseInt(index) + 1) : t
            }
          },
          {
            title: this.$t('reportQuery.documentNo'), dataIndex: 'number', width: 100,
            scopedSlots: { customRender: 'numberCustomRender' },
          },
          {title:this.$t('reportQuery.barcode'), dataIndex: 'barCode', width: 80},
          {title:this.$t('reportQuery.name'), dataIndex: 'mname', width: 100},
          {title:this.$t('reportQuery.specification'), dataIndex: 'standard', width: 100},
          
          {title:this.$t('reportQuery.model'), dataIndex: 'model', width: 60, ellipsis:true},
          {title:this.$t('reportQuery.unit'), dataIndex: 'materialUnit', width: 60, ellipsis:true},
          { title: this.$t('reportQuery.category'), dataIndex: 'categoryName',width:80 },
          {title:this.$t('reportQuery.warehouse'), dataIndex: 'dname', width: 80, ellipsis:true},
          {title:this.$t('reportQuery.warehousingDate'), dataIndex: 'operTimeStr', width: 150},
          {title:this.$t('warehouseManagement.breakNumber'), dataIndex: 'differNumber', width: 80},
          
          {title:this.$t('otherJS.DocumentType'), dataIndex: 'newType', width: 80,
            customRender:function (t,r,index) {
              let flag = getLanCode() === 'en'
              // let text = t.replace(/入库/g,'')
              return flag ? accountReportType[t] || t : t
            }
          },
          {title:this.$t('defaultTranslate.operator'), dataIndex: 'loginName', width: 80},
          {title:this.$t('reportQuery.remarks'), dataIndex: 'priceNote', width: 100, ellipsis:true,
            customRender:function (t,r,index) {
              let flag = getLanCode() === 'en'
              // let text = t.replace(/入库/g,'')
              return flag ? billDetailRemarks[t] || t : t
            }
        }
        ],
        url: {
          list: "/depotHead/findCheckMaterialDetail",
        },
      dataSource: [],
      dataSourceDetail: []
    }
  },
  created() {
  },
  methods: {
    moment,
    initCustomer () {
      let that = this
      findBySelectCus({}).then(res => {
        if (res) {
          that.cusList = res
        }
      })
    },
    show(params,record,btnEnableList) {
      this.btnEnableList = btnEnableList
      this.queryParam.depotId = record.depotId || ''
      this.defaultTimeStr = this.queryParam.createTimeRange
      this.queryParam.materialId = record.materialId
      this.queryParam.beginTime = params.beginTime
      this.queryParam.endTime = params.endTime
      this.queryParam = Object.assign({},this.queryParam)
      this.initCustomer()
      this.getAnotherDepotData()
      this.initUser()
      this.loadData(1)
      this.visible = true
    },


    getType: function () {
      const checkboxArr = [];
      if (checkboxArr.includes(this.queryParam.prefixNo)) {
        return 'checkbox'
      }
      return 'radio';
    },

    myHandleDetail(record) { 
      findBillDetailByNumber({ number: record.number }).then((res) => {
        if (res && res.code === 200) {
          let type = res.data.depotHeadType
          type = type.replace('其它', '')
          this.$refs.billDetail.show(res.data, type)
          this.$refs.billDetail.title = type + "-" + '详情'
        }
      })
    },
    setColumns(columns,columnsDetail){
      if(columns && columns.length){
        this.columns = columns
      }
      if(columnsDetail && columnsDetail.length){
        this.columnsDetail = columnsDetail
        console.log(this.columnsDetail,999);
      }
    },
    close() {
      this.$emit('close');
      this.visible = false;
    },
    handleCancel() {
      this.close()
    },
    onSelectChange(selectedRowKeys,selectedRows) {
      console.log(selectedRowKeys,666);
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows.map(v=>v.id)
    },
    onSelectDetailChange(selectedRowKeys) {
      this.selectedDetailRowKeys = selectedRowKeys;
    },
    organChenge(e){
      let arr = this.dataSourceDetail.filter(v=>v.organId === e)
      this.selectedDetailRowKeys = arr.map(v=>v.id)
    },
    handleOk() {
      
    },
    onDateChange: function (value, dateString) {
        this.$set(this.queryParam,'beginTime',dateString[0])
        this.$set(this.queryParam,'endTime',dateString[1])
        this.loadData(1)
    },
    onDateOk(value) {
      console.log(value);
    },
    searchReset() {
      this.queryParam = {
        organId: undefined,
        creator:undefined,
        beginTime: getNowFormatYear() + '-01-01',
        endTime: moment().format('YYYY-MM-DD'),
      }
      this.loadData(1);
    },
    getSelectBillRows() {
      let dataSource = this.dataSource;
      this.selectBillRows = [];
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedRows.includes(dataSource[i].id)) {
          this.selectBillRows.push(dataSource[i]);
        }
      }
    },
    getSelectBillDetailRows() {
      let dataSource = this.dataSourceDetail;
      this.selectBillDetailRows = [];
      for (let i = 0, len = dataSource.length; i < len; i++) {
        if (this.selectedDetailRowKeys.includes(dataSource[i].id)) {
          this.selectBillDetailRows.push(dataSource[i]);
        }
      }
    },
    rowAction(record, index) {
      return {
        on: {
          click: () => {
            let arr = []
            arr.push(record.id)
            this.selectedRowKeys = arr
          },
          dblclick: () => {
            if (this.noNeedNextDialogArray.includes(this.queryParam.prefixNo)) {
              this.$emit('ok', [record])
              this.close()
              return
            }
            let arr = []
            arr.push(record.id)
            this.selectedRows = arr
            this.handleOk()
          }
        }
      }
    },
    
    
    
    getQueryParams() {
        this.queryParam.subType = this.queryParam.subType || '' 
        this.queryParam.creator = this.queryParam.creator || '' 
        let param = Object.assign({}, this.queryParam, this.isorter);
        param.field = this.getQueryField();
        param.currentPage = this.ipagination.current;
        param.pageSize = this.ipagination.pageSize-1;
        return param;
      },
    loadData (arg) {
      console.log(this.url.list)
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }

      var params = this.getQueryParams() //查询条件
      
      this.loading = true
      getAction(this.url.list, params).then(res => {
        if (res.code === 200) {
          this.dataSource = res.data.rows.map(item => {
            !item.receivedQuantity && (item.receivedQuantity = 0)
            item.notReceived = item.total - item.receivedQuantity
            !item.billNo && (item.billNo = item.defaultNumber)
            return item
          })
          this.ipagination.total = res.data.total
          this.tableAddTotalRow(this.columns, this.dataSource)
        }
        if (res.code === 510) {
          this.$message.warning(res.data)
        }
        this.loading = false
      })
    },
    getAnotherDepotData() {
      getAction('/depot/findDepotList').then(res => {
        if (res.code === 200) {
          this.anotherDepotList = res.data
          let creator = this.getLocalStorage('pro__Login_Userinfo').tenantId
          this.selfDepot = this.anotherDepotList.filter(v=>v.tenantId === creator)
          this.othoerDepot = this.anotherDepotList.filter(v=>v.tenantId !== creator)
        } else {
          this.$message.info(res.data)
        }
      })
    },
    
    // 获取localStorage数据
    getLocalStorage (key) {
      var value = localStorage.getItem(key) // 取回 value 变量
      this.localStorageKeyJson = JSON.parse(value)
      return this.localStorageKeyJson.value
    },
    initUser () {
        getUserList({}).then((res) => {
          this.userList = res
        })
      },
      async exportExcel() {
        let aoa = [this.columns.map(v=>v.title)]
        this.downLoading = true
        // 获取要导出的数据
        let dataSource = await this.loadAllData(1)
        this.downLoading = false
        for (let i = 0; i < dataSource.length; i++) {
          let item = []
          for (let l = 0; l < this.columns.length; l++) {
            let column = this.columns[l]
              let text = dataSource[i][column.dataIndex] || ''
              // 有自定义方法
              if(typeof(column.customRender) ==="function"){
                let res = column.customRender(text,dataSource[i])
                // 返回的是node节点
                if(res && typeof(res.componentOptions)!="undefined"){
                  text = res.componentOptions.children[0].text
                }else{
                  text = res || ''
                }
              }
              item.push(text)
            
          }
          aoa.push(item)
        }
        openDownloadDialog(sheet2blob(aoa),this.title)
      },
  }
}
</script>

<style scoped>

</style>